class UsersController < ApplicationController
  before_filter :admin_required

  # GET /users
  # GET /users.xml
  def index
    @users = User.find(:all, :order => :name)

    respond_to do |format|
      format.html # index.html.erb
      format.xml  { render :xml => @users }
    end
  end

  # GET /users/1
  # GET /users/1.xml
  def show
    @user = User.find(params[:id])

    respond_to do |format|
      format.html # show.html.erb
      format.xml  { render :xml => @user }
    end
  end

  # GET /users/new
  # GET /users/new.xml
  def new
    @user = User.new

    respond_to do |format|
      format.html # new.html.erb
      format.xml  { render :xml => @user }
    end
  end

  # GET /users/1/edit
  def edit
    @user = User.find(params[:id])
  end

  # POST /users
  # POST /users.xml
  def create
    @user = User.new(params[:user])
	if @user.roles_mask == 0
	  @user.roles = %w[Administrator]
	elsif @user.roles_mask == 1
	  @user.roles = %w[Moderator]
	elsif @user.roles_mask == 2
	  @user.roles = %w[User]
	end

    respond_to do |format|
      if @user.save
	    flash[:notice] = "User #{@user.name} was successfully created."
        format.html { redirect_to(:action => 'index') }
        format.xml  { render :xml => @user, :status => :created, :location => @user }
      else
        format.html { render :action => "new" }
        format.xml  { render :xml => @user.errors, :status => :unprocessable_entity }
      end
    end
  end
  
  # PUT /users/1
  # PUT /users/1.xml
  def update
    # TODO: Clean up this code. Why do I have to create a new user to edit his or her info?
	# 1, 2, and 4, not 0, appear in the DB for roles_mask. A bug.
    @user = User.find(params[:id])
	@pass = @user.hashed_password
	@salt = @user.salt
	@user.destroy
	@user = User.new(params[:user])
	if @user.roles_mask == 0
	  @user.roles = %w[Administrator]
	elsif @user.roles_mask == 1
	  @user.roles = %w[Moderator]
	elsif @user.roles_mask == 2
	  @user.roles = %w[User]
	end
	@user.hashed_password = @pass
	@user.salt = @salt
	
    respond_to do |format|
      if @user.save # @user.update_attributes(params[:user])
	    # flash[:notice] = "#{@user.roles_mask}"
	    flash[:notice] = "User #{@user.name} was successfully updated."
        format.html { redirect_to(:action => 'index') }
        format.xml  { head :ok }
      else
        format.html { render :action => "edit" }
        format.xml  { render :xml => @user.errors, :status => :unprocessable_entity }
      end
    end
  end

  # DELETE /users/1
  # DELETE /users/1.xml
  def destroy
    @user = User.find(params[:id])
    @user.destroy

    respond_to do |format|
      format.html { redirect_to(users_url) }
      format.xml  { head :ok }
    end
  end
end
